package cn.edu.zut.soft.graduate.interceptor;

import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import cn.edu.zut.soft.graduate.log.LoginPathServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by chuchuang on 16/10/30.
 */
@Component
public class LoginHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

    @Autowired
    private LoginPathServiceImpl logService;

    public LoginHandlerInterceptorAdapter() {
        super();
    }

    /**
     * 所有未登录的用户无法操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获得请求路径的uri
        String uri = request.getRequestURI();

        // 判断路径是登出还是登录验证，是这两者之一的话执行Controller中定义的方法
        if (uri.endsWith("/login") || uri.endsWith("/logout")) {
            return true;
        }

        LoginVO loginVO = (LoginVO) request.getSession().getAttribute("user");

        if (loginVO == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        } else {
            //进行登录日志记录
            logService.behaviour(request,response,null);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
